<script lang="ts">
  import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';

  export default {
    name: 'KtImageUpload',
    components: {
      PlusOutlined,
      LoadingOutlined,
    },
  };
</script>

<script lang="ts" setup>
  import { computed, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { useInjectFormItemContext } from 'ant-design-vue/es/form';
  import { ContentAPI } from '@/api/ContentController';

  const props = defineProps({
    accept: {
      type: String,
      default: '.png,.jpg,.jpeg',
    },
    value: {
      type: String,
      required: true,
    },
  });
  const emits = defineEmits(['change']);

  const { onFieldChange } = useInjectFormItemContext();

  const uploading = ref(false);

  const imgUrl = computed({
    get: () => props.value,
    set: (value) => {
      emits('change', value);
      onFieldChange();
    },
  });
  const fileList = ref<any[]>([]);
  watch(() => imgUrl.value, (value) => {
    if (value) fileList.value = [{ url: imgUrl.value }];
    else fileList.value = [];
  }, { immediate: true });

  const handleFileUpload = ({ file, onSuccess, onError }) => {
    // 文件大小 m
    const fileSize = file.size / 1024 / 1024;
    if (fileSize > 2) {
      message.error('文件不能大于2m');
      setTimeout(() => {
        onError();
      }, 500);
      return;
    }
    const formData = new FormData();
    formData.append('file', file);
    ContentAPI.uploadPictureUsingPOST(formData)
      .then((res) => {
        imgUrl.value = res.data?.imgUrl ?? '';
        onSuccess();
      })
      .catch((err) => onError(err))
      .finally(() => uploading.value = false);
  };
</script>

<template>
  <a-upload
    :accept="props.accept"
    :disabled="uploading"
    :max-count="1"
    list-type="picture-card"
    :custom-request="handleFileUpload"
    :file-list="fileList"
    @remove="() => imgUrl = ''"
  >
    <div>
      <loading-outlined v-if="uploading" />
      <plus-outlined v-else />
    </div>
  </a-upload>
</template>
